import React, { useState, useContext } from 'react';
import {
  Input,
  Button,
  Drawer,
  Form,
  Radio,
  Divider,
  Table,
  Select,
  message,
  Typography,
  Popconfirm,
} from 'antd';
import { connect, useDispatch } from 'umi';
import { MOBILE_REG, EMAIL_REG } from '@/utils/const';
import OrgTreeSelect from '@/components/OrgTreeSelect';
import useEnum from '@/hooks/useEnum';
import styles from './StaffManageAddEdit.less';

const { Option } = Select;

const EditableCell = ({
  editing,
  dataIndex,
  title,
  record,
  index,
  children,
  handleTreeChange,
  handleSelectChange,
  handlePrimaryChange,
  positionList = [],
  ...restProps
}) => {
  if (editing) {
    if (dataIndex === 'orgName') {
      return (
        <td {...restProps}>
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `请选择${title}!`,
              },
            ]}
          >
            <OrgTreeSelect
              placeholder="请选择"
              dropdownMatchSelectWidth={false}
              dropdownStyle={{ maxWidth: 400 }}
              onSelect={handleTreeChange}
            />
          </Form.Item>
          {/* <Form.Item name='employeeOrgId' hidden>
            <Input />
          </Form.Item> */}
        </td>
      );
    }
    if (dataIndex === 'positionName') {
      return (
        <td {...restProps}>
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `请选择${title}!`,
              },
            ]}
          >
            <Select placeholder="请选择" onSelect={handleSelectChange}>
              {positionList.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </td>
      );
    }
    if (dataIndex === 'isPrimaryOrg') {
      return (
        <td {...restProps}>
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `请选择${title}!`,
              },
            ]}
          >
            <Select placeholder="请选择" onSelect={handlePrimaryChange}>
              <Option value="Y">主部门</Option>
              <Option value="N">兼职部门</Option>
            </Select>
          </Form.Item>
        </td>
      );
    }
  }
  return <td {...restProps}>{children}</td>;
};

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const validateMessages = {
  // eslint-disable-next-line no-template-curly-in-string
  required: '${label}是必填项!',
};

const StaffManageAddEdit = (props) => {
  const { drawerType, editData, lookDisabled, handleCloseDrawer } = props;
  const [form] = Form.useForm();
  const [formEdit] = Form.useForm();
  const dispatch = useDispatch();
  const [positionList, setPositionList] = useState([]);
  const [tableVisible] = useState(true);
  const [orgListData, setOrgListData] = useState(
    drawerType === 'add'
      ? []
      : editData.orgAndPositionList?.map((d, i) => ({ ...d, key: `key${i}` })) || [],
  );
  const [editingKey, setEditingKey] = useState('');
  const isEditing = (record) => record.key === editingKey;
  // 是否是新增组织后首次编辑，如果是，点击取消删除该记录，如果是新增记录保存后再次编辑，不删除
  const [isFirstAddEdit, setIsFirstAddEdit] = useState(false);

  const components = {
    body: {
      cell: EditableCell,
    },
  };

  const educationEnum = useEnum('100');
  const professionalTitleEnum = useEnum('200');
  const genderEnum = useEnum('300');
  const politicalFaceEnum = useEnum('400');

  const returnTitle = (type) => {
    if (type === 'add') {
      return '添加员工';
    } else if (type === 'edit') {
      return '编辑员工';
    }
    return '查看员工';
  };

  const handleSubmit = () => {
    const { validateFields } = form;

    validateFields().then((values) => {
      const list = [];
      const subList = [...orgListData];
      // 非空校验
      if (
        !subList.every(
          (item) =>
            (item.employeeOrgId === 0 || item.employeeOrgId) &&
            (item.employeePositionId === 0 || item.employeePositionId) &&
            (item.isPrimaryOrg === 0 || item.isPrimaryOrg),
        )
      ) {
        message.warning('组织信息数据不能为空');
        return;
      }
      // if (!subList.every((d) => Object.values(d).every((e) => e === 0 || !!e))) {
      //   message.warning('组织数据不能为空');
      //   return;
      // }
      // 必须有且只能有一个主部门
      if (!subList.some((d) => d.isPrimaryOrg === 'Y')) {
        message.warning('组织信息必须存在一个主部门');
        return;
      }
      subList.forEach((item) => {
        if (item.employeeOrgId !== undefined && item.employeePositionId !== undefined) {
          list.push({
            orgId: item.employeeOrgId,
            positionId: item.employeePositionId,
            isPrimaryOrg: item.isPrimaryOrg,
          });
        }
      });
      // console.log(subList);
      // console.log(list);
      // return;
      const params = {
        orgAndEmployeeInfoList: list,
        ...values,
      };
      let subDrawerType = 'stuffManageModel/addStuff';
      if (drawerType !== 'add') {
        params.id = editData.id;
        subDrawerType = 'stuffManageModel/updateStuff';
      }
      dispatch({
        type: subDrawerType,
        payload: params,
      }).then((res) => {
        const { code, message: errMsg } = res;
        if (code === 0) {
          message.success(drawerType === 'add' ? '添加员工成功!' : '修改员工成功!');
          handleCloseDrawer(true);
        } else {
          message.error(errMsg);
        }
      });
    });
  };

  // 新增组织信息数据
  const addTableRow = () => {
    if (editingKey) {
      message.warning('存在正在编辑的数据！');
      return;
    }
    const data = {
      key: `new${orgListData.length + 1}`,
      employeeOrgId: undefined,
      employeePositionId: undefined,
      positionName: undefined,
      orgName: undefined,
      isPrimaryOrg: 'N',
    };
    if (drawerType === 'add') {
      setOrgListData([...orgListData, data]);
    } else if (drawerType === 'edit') {
      setOrgListData([...orgListData, data]);
    }
    formEdit.setFieldsValue({
      ...data,
    });
    setEditingKey(data.key);
    setPositionList([]);
    setIsFirstAddEdit(true);
  };

  const edit = (record) => {
    console.log(record);
    formEdit.setFieldsValue({
      ...record,
      isPrimaryOrg: record.isPrimaryOrg,
    });
    setEditingKey(record.key);
    setPositionList([]);
    // 获取选中行的岗位
    dispatch({
      type: 'stuffManageModel/searchPosition',
      payload: { orgId: record.employeeOrgId },
    }).then((res) => {
      const { code, data, message: errMsg } = res;
      if (code === 0) {
        setPositionList(data);
      } else {
        message.error(errMsg);
      }
    });
  };

  const cancel = () => {
    let newList = [];
    const editData = orgListData.find((d) => d.key === editingKey);
    // &&
    // (!editData.employeeOrgId || !editData.employeePositionId)
    if (editData.key.indexOf('new') !== -1 && isFirstAddEdit) {
      newList = orgListData.filter((item) => item.key !== editingKey);
      setOrgListData(newList);
    }
    setEditingKey('');
    setIsFirstAddEdit(false);
  };

  const save = async (key) => {
    try {
      const row = await formEdit.validateFields();
      setIsFirstAddEdit(false);
      setEditingKey('');
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const deleteRow = (record) => {
    const newList = orgListData.filter((item) => item !== record);
    setOrgListData(newList);
  };

  const handleTreeChange = (value, node) => {
    // 组织变更，编辑表单岗位重置，表格数据更新；是否主部门和已存在组织保持一致
    formEdit.setFieldsValue({
      positionName: undefined,
      isPrimaryOrg: orgListData.filter((org) => org.employeeOrgId === node.value)[0]?.isPrimaryOrg,
    });
    const newEditList = [...orgListData].map((item) => {
      if (item.key === editingKey) {
        return {
          ...item,
          employeeOrgId: node.value,
          orgName: node.title,
          employeePositionId: undefined,
          positionName: undefined,
          isPrimaryOrg: orgListData.filter((org) => org.employeeOrgId === node.value)[0]
            ?.isPrimaryOrg,
        };
      }
      return item;
    });
    setOrgListData(newEditList);
    setPositionList([]);

    dispatch({
      type: 'stuffManageModel/searchPosition',
      payload: { orgId: node.value },
    }).then((res) => {
      const { code, data, message: errMsg } = res;
      if (code === 0) {
        setPositionList(data);
      } else {
        message.error(errMsg);
      }
    });
  };
  
  const handleSelectChange = (value, node) => {
    const newEditList = [...orgListData].map((item) =>
      item.key === editingKey
        ? { ...item, employeePositionId: Number(node.key), positionName: node.children }
        : item,
    );
    setOrgListData(newEditList);
  };

  const handlePrimaryChange = (value) => {
    let newEditList = [];
    // 主部门只能且必须存在一个，组织相同的情况下，是否主部门应该保持一致
    const editData = orgListData.find((d) => d.key === editingKey);
    if (value === 'Y') {
      newEditList = [...orgListData].map((item) => {
        if (
          item.key === editingKey ||
          (editData.employeeOrgId === item.employeeOrgId &&
            item.employeePositionId === item.employeePositionId)
        ) {
          return { ...item, isPrimaryOrg: value };
        }
        return { ...item, isPrimaryOrg: 'N' };
      });
    } else if (value === 'N') {
      newEditList = [...orgListData].map((item) => {
        if (
          item.key === editingKey ||
          (editData.employeeOrgId === item.employeeOrgId &&
            item.employeePositionId === item.employeePositionId)
        ) {
          return { ...item, isPrimaryOrg: value };
        }
        return item;
      });
    }
    setOrgListData(newEditList);
  };

  const columns = [
    {
      title: '*组织',
      key: 'orgName',
      dataIndex: 'orgName',
      editable: true,
    },
    {
      title: '*组织编码',
      key: 'orgCode',
      dataIndex: 'orgCode',
      editable: true,
    },
    {
      title: '*岗位',
      key: 'positionName',
      dataIndex: 'positionName',
      editable: true,
    },
    {
      title: '*是否主部门',
      key: 'isPrimaryOrg',
      dataIndex: 'isPrimaryOrg',
      editable: true,
      render: (text) => (text === 'Y' ? '主部门' : text === 'N' ? '兼职部门' : ''),
    },
    {
      title: '操作',
      key: '',
      render: (text, record) => {
        const editable = isEditing(record);
        const actions = editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            {record.key.indexOf('new') > -1 && (
              <Popconfirm title="确定取消?" onConfirm={cancel}>
                <a>取消</a>
              </Popconfirm>
            )}
          </span>
        ) : (
          <>
            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
              编辑
            </Typography.Link>
            &nbsp;&nbsp;&nbsp;
            <Typography.Link disabled={editingKey !== ''} onClick={() => deleteRow(record)}>
              删除
            </Typography.Link>
          </>
        );
        return lookDisabled ? null : actions;
      },
    },
  ];

  const columnsData = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        positionList,
        editing: isEditing(record),
        handleTreeChange,
        handleSelectChange,
        handlePrimaryChange,
      }),
    };
  });

  return (
    <Drawer
      title={returnTitle(drawerType)}
      width={600}
      placement="right"
      onClose={handleCloseDrawer}
      visible
      footer={
        <div style={{ textAlign: 'right' }}>
          <Button onClick={handleCloseDrawer} style={{ marginRight: 8 }}>
            取消
          </Button>
          {drawerType === 'look' ? null : (
            <Button onClick={handleSubmit} type="primary">
              {drawerType === 'add' ? '添加' : '保存'}
            </Button>
          )}
        </div>
      }
    >
      <div className={styles.drawerWrapper}>
        <div className={styles.basicInfo}> 基本信息 </div>
        <Form {...layout} form={form} name="nest-messages" validateMessages={validateMessages}>
          <Form.Item
            label="工号"
            name="employeeCode"
            rules={[{ required: true }, { pattern: '^[0-9]*$', message: '工号为数字' }]}
            initialValue={editData.employeeCode}
          >
            <Input placeholder="请输入工号" disabled={lookDisabled} />
          </Form.Item>
          <Form.Item
            label="姓名"
            name="employeeName"
            rules={[{ required: true }]}
            initialValue={editData.employeeName}
          >
            <Input placeholder="请输入姓名" disabled={lookDisabled} />
          </Form.Item>
          <Form.Item
            label="员工性质"
            name="employeeType"
            rules={[{ required: true }]}
            initialValue={editData.employeeType}
          >
            <Radio.Group disabled={lookDisabled}>
              <Radio value={2}>内部</Radio>
              <Radio value={1}>外包</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label="性别"
            name="gender"
            rules={[{ required: true }]}
            initialValue={editData.gender}
          >
            <Select placeholder="请选择性别" disabled={lookDisabled}>
              {genderEnum.map((item) => (
                <Option key={item.code}>{item.name}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="政治面貌" name="politicalFace" initialValue={editData.politicalFace}>
            <Select placeholder="请选择政治面貌" disabled={lookDisabled}>
              {politicalFaceEnum.map((item) => (
                <Option key={item.code}>{item.name}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="学历" name="degree" initialValue={editData.degree}>
            <Select placeholder="请选择学历" disabled={lookDisabled}>
              {educationEnum.map((item) => (
                <Option key={item.code}>{item.name}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="职称"
            name="professionalTitle"
            initialValue={editData.professionalTitle}
          >
            <Select placeholder="请选择职称" disabled={lookDisabled}>
              {professionalTitleEnum.map((item) => (
                <Option key={item.code}>{item.name}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="英文名"
            name="employeeEnglishName"
            initialValue={editData.employeeEnglishName}
            rules={[
              {
                pattern: /^[A-Za-z]*(\s[A-Za-z]*)*$/g,
                message: '请不要输入英文字符和空格以外的字符',
              },
              { max: 255, message: '英文名不能超过 255 个字符' },
            ]}
          >
            <Input placeholder="请输英文名" disabled={lookDisabled} />
          </Form.Item>

          <Form.Item
            label="排序编号"
            name="employeeOrderNo"
            initialValue={editData.employeeOrderNo}
            rules={[{ pattern: /^[1-9][0-9]{0,3}$/g, message: '请输入 1 ~ 9999 范围内的正整数' }]}
          >
            <Input placeholder="请输排序编号" disabled={lookDisabled} />
          </Form.Item>

          <Form.Item
            label="联系电话"
            name="mobilePhone"
            rules={[
              { pattern: MOBILE_REG, message: '手机号不正确，请输入正确的手机号码！' },
              // { required: true },
            ]}
            initialValue={editData.mobilePhone}
          >
            <Input placeholder="请输入手机号码" maxLength={11} disabled={lookDisabled} />
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[{ pattern: EMAIL_REG, message: '请填写正确的邮箱！' }]}
            initialValue={editData.email}
          >
            <Input placeholder="请输入邮箱" disabled={lookDisabled} />
          </Form.Item>
          <Form.Item label="办公地点" name="officeAddress" initialValue={editData.officeAddress}>
            <Input placeholder="请输入办公地点" disabled={lookDisabled} />
          </Form.Item>
          <Form.Item label="办公室电话" name="officePhone" initialValue={editData.officePhone}>
            <Input placeholder="请输入办公电话" disabled={lookDisabled} />
          </Form.Item>
        </Form>
        <Divider />
        <div className={styles.orgInfo}>
          <span className={styles.orgTitle}>组织信息</span>
          {lookDisabled ? (
            <span />
          ) : (
            <span className={styles.toggleFont} onClick={addTableRow}>
              新增
            </span>
          )}
        </div>
        <div style={{ display: tableVisible ? 'block' : 'none' }}>
          <Form form={formEdit} component={false}>
            <Table
              rowKey="key"
              components={components}
              columns={columnsData}
              dataSource={orgListData}
              pagination={false}
            />
          </Form>
        </div>
      </div>
    </Drawer>
  );
};

export default connect((state) => state)(StaffManageAddEdit);
